/**
 * 
 */
package com.shine.icis.blo.imp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.shine.cotrun.web.comm.ListPage;
import com.shine.cotrun.web.upload.FileDispatcher;
import com.shine.icis.blo.ISubmitLogService;
import com.shine.icis.dao.ISubmitLogDAO;
import com.shine.icis.dao.ISubmitReportDAO;
import com.shine.icis.dao.param.SubmitLogQueryParameters;
import com.shine.icis.exception.ICISException;
import com.shine.icis.hbean.SubmitLog;
import com.shine.icis.hbean.SubmitReport;
import com.shine.icis.hbean.SubmitFile;
import com.shine.icis.util.ZipHelper;

/**
 * @author zsy
 *
 */
public class SubmitLogService implements ISubmitLogService {
	
	private ISubmitLogDAO submitLogDAO;
	private ISubmitReportDAO submitReportDAO;

	public void setSubmitLogDAO(ISubmitLogDAO submitLogDAO) {
		this.submitLogDAO = submitLogDAO;
	}
	
	public void setSubmitReportDAO(ISubmitReportDAO submitReportDAO) {
		this.submitReportDAO = submitReportDAO;
	}
	
	@Override
	public SubmitLog getSubmitLogById(String id) {
		SubmitLog log =  submitLogDAO.findById(id);
		if (log != null) {
			log.getSubmitFiles().size();//加载集合
		}
		return log;
	}
	
	@Override
	public ListPage<SubmitLog> getSubmitLogPage(SubmitLogQueryParameters qp) {
		ListPage<SubmitLog> logs = submitLogDAO.findSubmitLogPage(qp);
		if (logs.isEmpty()) {
			return logs;
		}
		for (SubmitLog log : logs.getDataList()) {
			log.getSubmitFiles().size();//加载集合
		}
		return logs;
	}
	
	@Override
	public SubmitReport getSubmitReportBySubmitLogId(String logId) {
		if (logId == null) {
			return null;
		}
		return submitReportDAO.findBySubmitLogId(logId);
	}

	@Override
	public String csCompressSubmitFiles(String logId) throws ICISException {
		if (logId == null) {
			throw new IllegalArgumentException();
		}
		SubmitLog log =  submitLogDAO.findById(logId);
		String zipName = log.getDataDate() + "_" + log.getInternalVersion() + ".zip";
		List<File> filePaths = new ArrayList<File>();
		for (SubmitFile sf : log.getSubmitFiles()) {
			File f = new File(sf.getBackPath());
			if (!f.isFile()) {
				throw new ICISException("生成文件不存在，可能已超过备份时间");
			}
			filePaths.add(f);
		}
		File temDir = new File(FileDispatcher.getTempDir());
		if (!temDir.exists()) {
			temDir.mkdirs();
		}
//		System.out.println(zipName + "...........");
//		System.out.println(FileDispatcher.getTempDir() + zipName);
		ZipHelper.compressFiles(filePaths, FileDispatcher.getTempDir() + zipName);
		return FileDispatcher.getTempAbsDir() + zipName;
	}
}
